package com.own.component.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

/**
 * DataUtil
 *
 * @author chenxueli
 * @date 2022-06-15 03:14:15
 */
public class DataUtil {

    /**
     * 将byte数组转换成string类型表示
     *
     * @param src
     * @return
     */
    private static String bytesToHexString(byte[] src) {
        StringBuilder builder = new StringBuilder();
        if (src == null || src.length <= 0) {
            return null;
        }
        String hv;
        for (int i = 0; i < src.length; i++) {
            // 以十六进制（基数 16）无符号整数形式返回一个整数参数的字符串表示形式，并转换为大写
            hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
            if (hv.length() < 2) {
                builder.append(0);
            }
            builder.append(hv);
        }

        return builder.toString();
    }

    /**
     * 将Hex String转换为Byte数组
     *
     * @param hexString the hex string
     * @return the byte []
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (StringUtils.isEmpty(hexString)) {
            return null;
        }
        hexString = hexString.toLowerCase();
        final byte[] byteArray = new byte[hexString.length() >> 1];
        int index = 0;
        for (int i = 0; i < hexString.length(); i++) {
            if (index > hexString.length() - 1) {
                return byteArray;
            }
            byte highDit = (byte) (Character.digit(hexString.charAt(index), 16) & 0xFF);
            byte lowDit = (byte) (Character.digit(hexString.charAt(index + 1), 16) & 0xFF);
            byteArray[i] = (byte) (highDit << 4 | lowDit);
            index += 2;
        }
        return byteArray;
    }

    /**
     * 获取字符串的打印长度
     *
     * @param content 字符串
     * @return 打印长度
     */
    public static int getPrintLength(String content) {
        if (StringUtils.isBlank(content)) {
            return 0;
        }
        // 字符串原本的长度
        var length1 = content.length();
        // 获取中文
        var regex = "[^\\x00-\\xff]";
        var pattern = Pattern.compile(regex);
        var matcher = pattern.matcher(content);
        var length2 = matcher.results().count();
        return (int) length2 + length1;
    }

}
